package com.yunxin.admin.system.api.system;

import cn.hutool.core.io.FileUtil;
import com.yunxin.admin.system.application.OssService;
import com.yunxin.admin.system.application.dto.FileInfoDTO;
import com.yunxin.admin.system.infra.common.constant.SecurityConstants;
import com.yunxin.common.result.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;

/**
 * @author zero°
 * @since 2023-05-22
 */
@Tag(name = "07.文件接口")
@Slf4j
@RestController
@RequestMapping("/api/v1/files")
@RequiredArgsConstructor
public class FileController {

    private final OssService ossService;

    @PostMapping
    @Operation(summary = "文件上传", security = {@SecurityRequirement(name = SecurityConstants.TOKEN_KEY)})
    public Result<FileInfoDTO> uploadFile(@Parameter(description = "表单文件对象") @RequestParam(value = "file") MultipartFile file,
                                          @Parameter(description = "文件类型 1.文件 2.图片") @RequestParam(value = "type") int type) {
        String suffix = FileUtil.getSuffix(file.getOriginalFilename());
        try(InputStream inputStream = file.getInputStream()) {
            FileInfoDTO fileInfoDTO = ossService.uploadFile(suffix, inputStream, type);
            FileInfoDTO dto = new FileInfoDTO();
            dto.setName(fileInfoDTO.getName());
            dto.setUrl(fileInfoDTO.getUrl());
            return Result.success(dto);
        } catch (Exception e) {
            log.error("文件上传异常", e);
            return Result.failed();
        }
    }

    @DeleteMapping
    @Operation(summary = "文件删除", security = {@SecurityRequirement(name = SecurityConstants.TOKEN_KEY)})
    @SneakyThrows
    public Result<Boolean> deleteFile(@Parameter(description = "文件路径") @RequestParam String filePath) {
       boolean result = ossService.deleteFile(filePath);
        return Result.judge(result);
    }
}
